#include "configRequest.h"
#include "heartRequest.h"

char **gatewayip;
gchar *sn = NULL;

char *getgatewayip(){
    if(gatewayip != NULL)
    {
        return gatewayip;
    }
    GKeyFile *configiniPath=g_key_file_new();
    if(!g_key_file_load_from_file(configiniPath,"./config.ini",G_KEY_FILE_NONE,NULL)){
      g_warning("load config.ini error!");
      return NULL;
    }
    gchar *path =g_key_file_get_string(configiniPath,"config","devinfo_path",NULL);
    g_key_file_free(configiniPath);

    //2.去devinfo_path指定的文件中读取 ip 和 地址
    GKeyFile *configPath =  g_key_file_new();
    if(!g_key_file_load_from_file(configPath,path,G_KEY_FILE_NONE,NULL)){
      g_warning("load config.ini error!");
      return NULL;
    }
    gatewayip= g_key_file_get_string(configPath,"config","gatewayip",NULL);
    
    g_key_file_free(configPath);
    return gatewayip;
}

//缓存sn
gchar * getDiviceSn(){
/*   if (sn!=NULL)
   {
      return sn;
   }
   FILE *file = fopen("/sys/class/dmi/id/product_serial","r");
   char *sn = (char*)calloc(1,256); 
   //读取一行数据
   fgets(sn,256,file);
   fclose(file);
   g_print("sn=%s\n",sn);*/
   return "jfjjfjfjjfjfjfjf";
}

void * recvMsgAndSendConfig(void* param)
{
    while (1)
    {
        printf("wait boa msg:\n");
        int mqId = getMsgQueue(PATHNAME_BOA_MAIN,PROCESS_ID_BOA_MAIN);
    if (mqId == -1)
    {
      perror("create mq error");
      return -1;
    }
    Message msg={

    };
    int recSize = recvMsg(mqId,&msg,MSG_SIZE);
    if (recSize == -1)
    {
        perror("recv msg error");
    }  
    printf("收到消息\n"); 
    
    sendConfigRequest();
    }
}

int main(int argc, char const *argv[])
{
    pthread_t tid;
    pthread_create(&tid,NULL,recvMsgAndSendConfig,NULL);

    while(1)
    {
        char* ip=getgatewayip();
        char* sn=getDiviceSn();
        sendHeartRequest(ip,sn);
        sleep(5);
    }
    
    return 0;
}
